﻿# 必须使用 bom 否则不支持中文。据说 6.0 以上版本已经不用了，但系统默认是 5.1 版本并且不再更新。

# 激活操作系统
function activeOS () {
    $activationStatus = cscript.exe /nologo C:\Windows\System32\slmgr.vbs /dli 2>&1
    if ($activationStatus.count -gt 5) {
        $activationStatus = $activationStatus[4].split(":")[-1].Trim()
    }
    $osIsActivated = "已授权","licensed" -contains $activationStatus
    if ($osIsActivated) {
        Write-Host "系统已经激活，不需要运行激活脚本。" -ForegroundColor Green
        [Environment]::NewLine
    } else {
        irm https://get.activated.win | iex
    }
}

function add_to_path($dir, $envPathName="Path", $scope="User") {
    # envPath 可以是 path， psmodulepath, lz_Path等路径类变量
    # $scope 可以是 User, Machine, Process
    if (! $dir) {
        Write-Host "no path to add!"
        return
    }
    $envPath = [Environment]::GetEnvironmentVariable($envPathName, $scope)
    $dir = [Environment]::ExpandEnvironmentVariables($dir)
    if (! $envPath) {
        $envPath = "$dir"
    } elseif ($envPath -notlike "*$dir*") {
        $envPath = "$dir;" + $envPath
    }
    [Environment]::SetEnvironmentVariable($envPathName, $envPath, $scope)
}
add_to_path "$env:scoop\modules" "PsModulePath"
add_to_path "$env:scoop\apps\msys2-cn\current\usr\bin" "Path"
add_to_path "$env:scoop\apps\msys2-cn\current\mingw64\bin" "Path"
add_to_path "$env:scoop\shims" "Path"
$env:path += ";$env:scoop\shims"

# 安装显卡驱动
function install_videoDriver () {
    # 安装显卡驱动
    $display = get-ciminstance -ClassName Win32_DisplayControllerConfiguration
    $notInstalled = $display.Name -like "*microsoft basic*"
    $inf = "$env:wsr\lzDrivers\Nvidia\20210913\nv_dispi.inf" 
    $infExisted = Test-Path $inf
    if ($infExisted -and $notInstalled) {
        Write-Host "installing vedio driver...."
        pnputil /add-driver $inf /install
    }
}
install_videoDriver

function set-swapDisk($diskLetter) {
    # 盘符要有冒号
    $swapfile = $diskLetter + "\pagefile.sys"
    # 禁用自动管理页面文件
    Set-CimInstance -InputObject (Get-CimInstance -ClassName Win32_ComputerSystem) -Property @{ AutomaticManagedPagefile = $false }
    # 删除所有交换文件
    Get-CimInstance -ClassName Win32_PageFileSetting | Remove-CimInstance
    # 添加新的页面文件
    New-CimInstance -classname Win32_PageFileSetting -Property @{Name = $swapfile}
}

# 安装打印机
function Install-Printer {
    $driverPath = $env:wsr + "\lzDrivers\hp1010printer\LaserJet_1010_1012_1015\x64\hpc1015w.inf"
    $driverName = "hp laserJet 1010 HB"
    $printerName = "lzHP1010HB"
    $printerPort = "p.z"
    $printerPortName = "lz_printerPort"

    if ($null -eq (Get-Printer -name $printerName -ErrorAction SilentlyContinue)) {
        # Check if driver is not already installed
        if ($null -eq (Get-PrinterDriver -name $driverName -ErrorAction SilentlyContinue)) {
          # Add the driver to the Windows Driver Store
          pnputil.exe /a $driverPath

          # Install the driver
          Add-PrinterDriver -Name $driverName
        } else {
          Write-Warning "打印机驱动 $($driverName) 已经存在。"
        }

        # Check if printerport doesn't exist
        if ($null -eq (Get-PrinterPort -name $printerPortName -ErrorAction SilentlyContinue)) {
          # Add printerPort
          Add-PrinterPort -Name $printerPortName -PrinterHostAddress $printerPort
        } else {
          Write-Warning "打印端口 $($printerPortName) 已经存在。"
        }

        try {
          # Add the printer
          Add-Printer -Name $printerName -DriverName $driverName -PortName $printerPortName -ErrorAction stop
        } catch {
          Write-Host $_.Exception.Message -ForegroundColor Red
          break
        }

        Write-Host "成功安装了打印机 $($printerName)！" -ForegroundColor Green
    } else {
     Write-Warning "打印机 $($printerName) 已经存在。"
    }
    [Environment]::NewLine
    get-printer
    [Environment]::NewLine
}
Install-Printer

# 删除小组件
Write-Host "删除小组件及卸载game bar" -ForegroundColor Green
Get-AppxPackage *MicrosoftWindows.Client.WebExperience* | Remove-AppxPackage
[Environment]::NewLine

# 增删可选功能
# Dism /online /Disable-Feature /FeatureName:TFTP /Remove
# DISM /Online /Enable-Feature /All /FeatureName:Microsoft-Hyper-V
[Environment]::NewLine

# 卸载 onedrive
Write-Host "卸载 onedrive" -ForegroundColor Green
function remove-onedrive {
    # 1. 终止 OneDrive 进程
    Stop-Process -Name "OneDrive*" -Force -ErrorAction SilentlyContinue

    # 2. 卸载 OneDrive 应用（适用于 Windows 10/11）
    if (Test-Path "$env:SystemRoot\System32\OneDriveSetup.exe") {
        Start-Process -FilePath "$env:SystemRoot\System32\OneDriveSetup.exe" -ArgumentList "/uninstall" -Wait -NoNewWindow
    }
    if (Test-Path "$env:SystemRoot\SysWOW64\OneDriveSetup.exe") {
        Start-Process -FilePath "$env:SystemRoot\SysWOW64\OneDriveSetup.exe" -ArgumentList "/uninstall" -Wait -NoNewWindow
    }

    # 3. 删除残留文件和文件夹
    $paths = @(
        "$env:LocalAppData\Microsoft\OneDrive",
        "$env:ProgramData\Microsoft OneDrive",
        "$env:UserProfile\OneDrive",
        "C:\OneDriveTemp"
    )
    foreach ($path in $paths) {
        if (Test-Path $path) {
            Remove-Item -Path $path -Recurse -Force -ErrorAction SilentlyContinue
        }
    }

    # 4. 清理注册表项
    $registryPaths = @(
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"
    )
    foreach ($regPath in $registryPaths) {
        if (Get-ItemProperty -Path $regPath -Name "OneDrive" -ErrorAction SilentlyContinue) {
            Remove-ItemProperty -Path $regPath -Name "OneDrive" -Force
        }
    }

    # 5. 禁用 OneDrive 自动启动（组策略方式，可选）
    if (Test-Path "HKLM:\Software\Policies\Microsoft\Windows\OneDrive") {
        Remove-Item -Path "HKLM:\Software\Policies\Microsoft\Windows\OneDrive" -Recurse -Force
    }
    New-Item -Path "HKLM:\Software\Policies\Microsoft\Windows\OneDrive" -Force | Out-Null
    Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\OneDrive" -Name "DisableFileSyncNGSC" -Type DWord -Value 1

    # 6. 删除计划任务
    Get-ScheduledTask -TaskName "*OneDrive*" -ErrorAction SilentlyContinue | Unregister-ScheduledTask -Confirm:$false

    Write-Host "OneDrive 已彻底删除！可能需要重启系统确保完全生效。" -ForegroundColor Green
}
remove-onedrive
[Environment]::NewLine

$vc = $env:wsr + "\lzDrivers\VC_redist.x64.exe"
if ( -not ( Test-Path -Path $vc ) )
{
    Write-Host "开始下载 vc_redist.x64.exe" -ForegroundColor Green
    iwr https://aka.ms/vs/17/release/vc_redist.x64.exe -outfile $vc
    Write-Host "vc_redist.x64.exe 下载完成。" -ForegroundColor Green
}
Write-Host "安装 vc_redist.x64.exe" -ForegroundColor Green
iex "$vc /quiet"
[Environment]::NewLine

# 这个声卡驱动存在于相关的机器上。其他机器上不该运行。
$audioDriver = $env:wsr + "\lzDrivers\Audio_9239_FF00\Setup.exe"
$audioDriverExisted = Test-Path $audioDriver
$audioDriverInstalled = Test-Path "C:\Program Files\Realtek\Audio\"
if ($audioDriverExisted -and -not $audioDriverInstalled) {
    Write-Host "安装声卡驱动" -ForegroundColor Green
    &($audioDriver) /S
}
[Environment]::NewLine

# 重置scoop。这之后个别软件还需要处理。
scoop reset *

set clink_profile="d:\temp\clink_profile"
setx clink_profile "d:\temp\clink_profile"
clink autorun install -- --quiet
clink set clink.autoupdate off

timeout 33
